package com.potenza.wxuser.aop;

import com.alibaba.fastjson.JSON;
import com.potenza.wxuser.annotation.RepeatSubmit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Aspect
public class RepeatAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    HttpServletRequest request;

    @Pointcut("@annotation(com.potenza.wxuser.annotation.RepeatSubmit)")
    public void repeatCheck(){}

    @Around(value = "repeatCheck()")
    public void check(ProceedingJoinPoint point) throws Throwable {

        System.out.println("========检验请求是否重复操作========");
        long start = System.currentTimeMillis();
        String key = "";
        try {
            //获取访问的方法
            Method method = ((MethodSignature) point.getSignature()).getMethod();
            //模拟获取登录用户Id
            String feature = getRequestFeature(request);
            //根据需求组合key
            key = method.toString()+":" + feature;
            //获取过期时间
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            //设置Redis的key

            boolean absent = redisTemplate.opsForValue()//setIfAbsent 如果没有 设置，返回true
                    .setIfAbsent(key,"userInfo",
                    annotation.limit(),
                    TimeUnit.SECONDS);
            if(!absent){
                throw new IllegalArgumentException("请勿重复提交");
            }
            String name = point.getSignature().getName();
            System.out.printf("========方法名：{%s},开始执行========",name);
            Object result = point.proceed();
            System.out.printf("========{%s}方法执行完毕,执行结果：{%s},共耗时：{%d}ms======",
                    name, JSON.toJSONString(result),
                    System.currentTimeMillis()-start);
            System.out.println();
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }finally {
            //redisTemplate.delete(key);
        }
    }

    public String getRequestFeature(HttpServletRequest request){
        // 本次参数及系统时间
        String url = request.getRequestURI();
        String nowParams = JSON.toJSONString(request.getParameterMap());

        return url+":" + nowParams;
    }

}